package com.lanhai.javaBean;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.lanhai.model.Path;
import com.mybatis.dao.PathDao;
import com.mybatis.dao.PathLockDao;

public class PathBean {

	/**
	 * 加载地标列表
	 */
	public static List<Path> loadData(SqlSessionFactory sqlSessionFactory) {
		List<Path> mapPathList = new ArrayList<Path>();
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			PathDao dao = sqlSession.getMapper(PathDao.class);
			List<Map<String, Object>> list = dao.selectAll();
			if (list.size() > 0) {
				for (Map<String, Object> m : list) {
					Path mp = new Path();
					mp.setId((Integer) m.get("id"));
					mp.setName((String) m.get("name"));// 名称
					mp.setKey((String) m.get("key"));// 关键字
					mp.setItem((Integer) m.get("item"));// 线路编号
					mp.setNodeArr((String) m.get("nodeArr"));// 路径的结点数组，用逗号分隔节点ID
					String itemNote = (String) m.get("itemNote");// 对应交管区ID
					if (itemNote != null) {
						String[] itemNoteArr = itemNote.split(",");
						if (itemNoteArr.length > 0) {
							String[] itemNotes = new String[itemNoteArr.length];
							for (int i = 0; i < itemNoteArr.length; i++) {
								if (!itemNoteArr[i].equals("")) {
									itemNotes[i] = itemNoteArr[i];
								}
							}
							mp.setItemNote(itemNotes);
						}
					}
					mapPathList.add(mp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
		return mapPathList;
	}

	/**
	 * 更新路线
	 * 
	 * @param sqlSessionFactory
	 */
	public static void updatePathLock(SqlSessionFactory sqlSessionFactory) {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			// InputStream is =
			// ChargerBean.class.getClass().getResourceAsStream("/data/agvList.csv");
			// BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String filePath = "d:/agvData/slam_route.csv";
			BufferedReader reader = new BufferedReader(new FileReader(filePath));// 换成你的文件名
			reader.readLine();// 第一行信息，为标题信息，不用，如果需要，注释掉
			String line = null;
			PathLockDao dao = sqlSession.getMapper(PathLockDao.class);
			while ((line = reader.readLine()) != null) {
				String item[] = line.split(",");// CSV格式文件为逗号分隔符文件，这里根据逗号切分
				int items = Integer.parseInt(item[0]);
				String key = item[1];
				String name = item[2];

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("item", items);
				map.put("key", key);
				map.put("name", name);
				dao.updatePathLock(map);
				sqlSession.commit();
				// System.out.println("num:" + item[0] + ",x:" + item[1] + "[" + mapX + "]" +
				// ",y:" + item[2]);
				// }
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
	}
}
